/**    
 * @{#} RemoteImageDownloader.java Create on 2013-7-3 上午9:10:14    
 *        
 * @author Evan
 *
 * @email evan0502@qq.com
 *
 * @version 1.0    
 */
package com.evan.common.connection.remotefile;

import java.lang.ref.SoftReference;
import java.util.Locale;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import cn.skinapp.R;

import com.evan.common.connection.ConnectionCommon;
import com.evan.common.connection.Net;
import com.evan.common.constant.Constant;
import com.evan.common.handler.ImageHandler;
import com.evan.common.utils.CommonUtility;
import com.evan.common.utils.FilesUtil;
import com.evan.common.utils.ImageUtils;

public class RemoteImageDownloader {

	public static void download(final String path, final ImageHandler handler,
			final boolean isRoundCorner) {
		if (!CommonUtility.isNull(path)) {
			String name = getFileNameString(path, isRoundCorner);
			Bitmap bitmap = CommonUtility.getBitmapCache(name);
			if (bitmap != null) {
				Message m = Message.obtain();
				m.obj = name;
				handler.sendMessage(m);
				bitmap = null;
			} else {
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						load(path, handler, isRoundCorner);
					}
				}.start();
			}
		} else {
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		}
	}

	private static void load(String path, Handler handler, boolean isRoundCorner) {
		try {
			String name = getFileNameString(path, isRoundCorner);
			Bitmap bitmap = null;
			boolean isExists = FilesUtil.compare(name);
			if (!isExists) {
				Net net = new Net();
				byte[] data = net.downloadResource("http://www.dzzyl.cn/"
						+ path);
				if (!CommonUtility.isNull(data)) {
					bitmap = BitmapFactory.decodeByteArray(data, 0,
							data.length, ImageUtils.getOptionsTh(data));
					if (isRoundCorner) {
						Constant.imagesCache.put(
								name,
								new SoftReference<Bitmap>(ImageUtils
										.toRoundCorner(bitmap, 9)));
					} else {
						Constant.imagesCache.put(name,
								new SoftReference<Bitmap>(bitmap)); // 把下载好的图片保存到缓存中
					}
					FilesUtil.saveImage(name, data);
				} else {
					Message m = Message.obtain();
					m.obj = Constant.LOADING_IMG_FAIL_CODE;
					handler.sendMessage(m);
					return;
				}
			} else {
				String pp = FilesUtil.getRootPath() + name;
				bitmap = BitmapFactory.decodeFile(pp,
						ImageUtils.getOptionsTh(pp));
				if (isRoundCorner) {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							ImageUtils.toRoundCorner(bitmap, 9)));
				} else {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							bitmap)); // 把下载好的图片保存到缓存中
				}
			}
			Message m = Message.obtain();
			m.obj = name;
			handler.sendMessage(m);
		} catch (Exception e) {
			e.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		} catch (OutOfMemoryError err) {
			err.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
			System.err.println("out of memory error");
		}
	}

	public static void download4Java(final String path,
			final ImageHandler handler, final boolean isRoundCorner,
			final boolean isCompression) {

		if (!CommonUtility.isNull(path)) {
			String name = getFileNameString(path, isRoundCorner);
			Bitmap bitmap = CommonUtility.getBitmapCache(name);
			if (bitmap != null) {
				Message m = Message.obtain();
				m.obj = name;
				handler.sendMessage(m);
				bitmap = null;
			} else {
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						load4Java(path, handler, isRoundCorner, isCompression);
					}
				}.start();
			}
		} else {
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		}
	}

	private static void load4Java(String path, Handler handler,
			boolean isRoundCorner, boolean isCompression) {
		try {
			String name = getFileNameString(path, isRoundCorner);
			Bitmap bitmap = null;
			boolean isExists = FilesUtil.compare(name);
			if (!isExists) {
				Net net = new Net();
				String p = path.startsWith("http") ? path : ConnectionCommon
						.getInstance().REQUEST_PIC_PATH + path;
				byte[] data = net.downloadResource(p);
				if (!CommonUtility.isNull(data)) {
					if (!isCompression) {
						bitmap = BitmapFactory.decodeByteArray(data, 0,
								data.length);
					} else {
						bitmap = BitmapFactory.decodeByteArray(data, 0,
								data.length, ImageUtils.getOptionsTh(data));
					}
					if (isRoundCorner) {
						Constant.imagesCache.put(
								name,
								new SoftReference<Bitmap>(ImageUtils
										.toRoundCorner(bitmap, 1)));
					} else {
						Constant.imagesCache.put(name,
								new SoftReference<Bitmap>(bitmap)); // 把下载好的图片保存到缓存中
					}
					FilesUtil.saveImage(name, data);
				} else {
					Message m = Message.obtain();
					m.obj = Constant.LOADING_IMG_FAIL_CODE;
					handler.sendMessage(m);
					return;
				}
			} else {
				String pp = FilesUtil.getRootPath() + name;
				if (!isCompression) {
					bitmap = BitmapFactory.decodeFile(pp);
				} else {
					bitmap = BitmapFactory.decodeFile(pp,
							ImageUtils.getOptionsTh(pp));
				}

				if (isRoundCorner) {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							ImageUtils.toRoundCorner(bitmap, 1)));
				} else {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							bitmap)); // 把下载好的图片保存到缓存中
				}
			}
			Message m = Message.obtain();
			m.obj = name;
			handler.sendMessage(m);
		} catch (Exception e) {
			e.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		} catch (OutOfMemoryError err) {
			err.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
			System.err.println("out of memory error");
		}
	}

	public static void download4Java(final String path,
			final ImageHandler handler, final boolean isRoundCorner) {

		if (!CommonUtility.isNull(path)) {
			String name = getFileNameString(path, isRoundCorner);
			Bitmap bitmap = CommonUtility.getBitmapCache(name);
			if (bitmap != null) {
				Message m = Message.obtain();
				m.obj = name;
				handler.sendMessage(m);
				bitmap = null;
			} else {
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						load4Java(path, handler, isRoundCorner);
					}
				}.start();
			}
		} else {
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		}
	}

	private static void load4Java(String path, Handler handler,
			boolean isRoundCorner) {
		try {
			String name = getFileNameString(path, isRoundCorner);
			Bitmap bitmap = null;
			boolean isExists = FilesUtil.compare(name);
			if (!isExists) {
				Net net = new Net();
				String p = path.startsWith("http") ? path : ConnectionCommon
						.getInstance().REQUEST_PIC_PATH + path;
				byte[] data = net.downloadResource(p);
				if (!CommonUtility.isNull(data)) {
					bitmap = BitmapFactory.decodeByteArray(data, 0,
							data.length, ImageUtils.getOptionsTh(data));
					if (isRoundCorner) {
						Constant.imagesCache.put(
								name,
								new SoftReference<Bitmap>(ImageUtils
										.toRoundCorner(bitmap, 1)));
					} else {
						Constant.imagesCache.put(name,
								new SoftReference<Bitmap>(bitmap)); // 把下载好的图片保存到缓存中
					}
					FilesUtil.saveImage(name, data);
				} else {
					Message m = Message.obtain();
					m.obj = Constant.LOADING_IMG_FAIL_CODE;
					handler.sendMessage(m);
					return;
				}
			} else {
				String pp = FilesUtil.getRootPath() + name;
				bitmap = BitmapFactory.decodeFile(pp,
						ImageUtils.getOptionsTh(pp));
				if (isRoundCorner) {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							ImageUtils.toRoundCorner(bitmap, 1)));
				} else {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							bitmap)); // 把下载好的图片保存到缓存中
				}
			}
			Message m = Message.obtain();
			m.obj = name;
			handler.sendMessage(m);
		} catch (Exception e) {
			e.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		} catch (OutOfMemoryError err) {
			err.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
			System.err.println("out of memory error");
		}
	}

	public static void downloadImageWithName(final String path,
			final ImageHandler handler, final boolean isRoundCorner, String name) {
		try {
			Bitmap bitmap = null;
			boolean isExists = FilesUtil.compare(name);
			if (!isExists) {
				Net net = new Net();
				String p = path.startsWith("http") ? path : ConnectionCommon
						.getInstance().REQUEST_PIC_PATH + path;
				byte[] data = net.downloadResource(p);
				if (!CommonUtility.isNull(data)) {
					bitmap = BitmapFactory.decodeByteArray(data, 0,
							data.length, ImageUtils.getOptionsTh(data));
					if (isRoundCorner) {
						Constant.imagesCache.put(
								name,
								new SoftReference<Bitmap>(ImageUtils
										.toRoundCorner(bitmap, 1)));
					} else {
						Constant.imagesCache.put(name,
								new SoftReference<Bitmap>(bitmap)); // 把下载好的图片保存到缓存中
					}
					FilesUtil.saveImage(name, data);
				} else {
					Message m = Message.obtain();
					m.obj = Constant.LOADING_IMG_FAIL_CODE;
					handler.sendMessage(m);
					return;
				}
			} else {
				String pp = FilesUtil.getRootPath() + name;
				bitmap = BitmapFactory.decodeFile(pp,
						ImageUtils.getOptionsTh(pp));
				if (isRoundCorner) {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							ImageUtils.toRoundCorner(bitmap, 1)));
				} else {
					Constant.imagesCache.put(name, new SoftReference<Bitmap>(
							bitmap)); // 把下载好的图片保存到缓存中
				}
			}
			Message m = Message.obtain();
			m.obj = name;
			handler.sendMessage(m);
		} catch (Exception e) {
			e.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		} catch (OutOfMemoryError err) {
			err.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
			System.err.println("out of memory error");
		}
	}

	// 处理聊天记录的图片
	public static void downloadChatImage(final String path,
			final ImageHandler handler, final boolean isRoundCorner) {

		if (!CommonUtility.isNull(path)) {
			String name = getFileNameString(path, isRoundCorner);
			Bitmap bitmap = CommonUtility.getBitmapCache(name);
			if (bitmap != null) {
				((ImageView) handler.view).setImageBitmap(bitmap);
				handler.view.setTag(R.id.tag_filepath, FilesUtil.getRootPath()
						+ name);
			} else {
				new Thread() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						loadChatImage(path, handler, isRoundCorner);
					}
				}.start();
			}
		} else {
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		}
	}

	private static void loadChatImage(String path, Handler handler,
			boolean isRoundCorner) {
		try {
			String name = getFileNameString(path, isRoundCorner);
			if (CommonUtility.isNull(Constant.imagesCache.get(name))) {
				Bitmap bitmap = null;
				boolean isExists = FilesUtil.compare(name);
				if (!isExists) {
					Net net = new Net();
					byte[] data = net.downloadResource(ConnectionCommon
							.getInstance().REQUEST_PIC_PATH + path);
					if (!CommonUtility.isNull(data)) {
						FilesUtil.saveImage(name, data);
					} else {
						Message m = Message.obtain();
						m.obj = Constant.LOADING_IMG_FAIL_CODE;
						handler.sendMessage(m);
						return;
					}
				}
				bitmap = ImageUtils.getBitMap(FilesUtil.getRootPath() + name);
				Constant.imagesCache.put(name,
						new SoftReference<Bitmap>(bitmap));
				Message m = Message.obtain();
				m.obj = name;
				handler.sendMessage(m);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
		} catch (OutOfMemoryError err) {
			err.printStackTrace();
			Message m = Message.obtain();
			m.obj = Constant.LOADING_IMG_FAIL_CODE;
			handler.sendMessage(m);
			System.err.println("out of memory error");
		}
	}

	public static String getFileNameString(String path, boolean isRoundCorner) {
		String p = path.substring(path.lastIndexOf("/") + 1).toLowerCase(
				Locale.getDefault());
		int spe = p.lastIndexOf(".");
		String fileType = p.substring(spe);
		String name = p.substring(0, spe);
		StringBuilder sb = new StringBuilder(name);
		sb.append("_").append(isRoundCorner).append(fileType).append(".cache");
		// if (!fileType.toLowerCase(Locale.getDefault()).contains("mp4")
		// && !fileType.toLowerCase(Locale.getDefault()).contains("3gp")) {
		// sb.append(".cache");
		// }
		return sb.toString();
	}
}
